﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using HtmlAgilityPack;

namespace SimpleSocxs
{
    public static class Helper
    {
        public static string MapPath(string virtualPath) 
        {
            return System.Web.Hosting.HostingEnvironment.MapPath(virtualPath);
        }

        public static string GetPageUrlByID(int pageID)
        {
            var page = SocxsDataStore.Current.GetPageByID(pageID);
            var user = SocxsDataStore.Current.GetUserByID(page.UserID);

            return VirtualPathUtility.ToAbsolute("~/users/" + user.Name + "/" + page.Name);
        }

        public static string GetAssetUrl(int userID, string assetName)
        {
            var user = SocxsDataStore.Current.GetUserByID(userID);
            return VirtualPathUtility.ToAbsolute("~/users/" + user.Name + "/assets/" + assetName);
        }

        public static string InjectStreamPanels(string html)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            var nodes = doc.DocumentNode.SelectNodes("//div[contains(@class,'socxs_panel') and not(contains(@class,'socxs_panels'))]");
            
            if(nodes != null)
                foreach (HtmlNode node in nodes)
                {
                    var attrs = new List<string>();
                    //attrs.Add(CreateAttr(node, "RenderName"));
                    attrs.Add(CreateAttr(node, "StreamID"));
                    attrs.Add(CreateAttr(node, "Title"));

                    node.InnerHtml = @"<socxs:Item runat=""server"" " + string.Join(" ", attrs.ToArray()) + "/>";
                }

            var sbuf = new StringWriter();
            doc.Save(sbuf);
            return sbuf.ToString();
        }


        static string CreateAttr(HtmlNode node, string attrName)
        {
            foreach (HtmlAttribute attr in node.Attributes)
            {
                if(string.Equals(attr.Name, attrName, StringComparison.OrdinalIgnoreCase))
                    return attrName + "=\"" + attr.Value + '\"';
            }
            
            return string.Empty;            
        }

        public static string RemoveAllTags(string html) 
        {
            return Regex.Replace(html, "<[^>]*>", string.Empty);
        }

        //user folder first and shared folder
        public static string GetFileInUserAndShared(string userName, string filePath)
        {
            var fileInUser = "~/users/" + userName + "/" + filePath;
            if(File.Exists(MapPath(fileInUser)))
                return fileInUser;

            var fileInShared = "~/shared/" + filePath;
            if(File.Exists(MapPath(fileInShared)))
                return fileInShared;

            return string.Empty;
        }

        public static IEnumerable<string> GetFileNamesInUserAndShared(string userName, string filePath)
        {
            var path = Path.GetDirectoryName(filePath);
            var file = Path.GetFileName(filePath);
            var pathInUser = MapPath("~/users/" + userName + "/" + path);
            
            var filesInUser =  new string[0];
            if(Directory.Exists(pathInUser))
                filesInUser = file == string.Empty ? Directory.GetFiles(pathInUser) : Directory.GetFiles(pathInUser, file);
            
            var pathInShared = MapPath("~/shared/" + path);
            var filesInShared = new string[0];
            if(Directory.Exists(pathInShared))
                filesInShared = file == string.Empty ? Directory.GetFiles(pathInShared) : Directory.GetFiles(pathInShared, file);

            return new string[0]
                .Union(filesInUser.Select(_ => Path.GetFileName(_)))
                .Union(filesInShared.Select(_ => Path.GetFileName(_)));
        }

        public static DateTime ParseTwitterDateTime(string dateStr)
        {
            return DateTime.ParseExact(dateStr, "ddd MMM dd HH:mm:ss zz00 yyyy", System.Globalization.CultureInfo.InvariantCulture);
        }

        public static string GetHtml(this HtmlDocument doc)
        {
            var sbuf = new StringWriter();
            doc.Save(sbuf);
            return sbuf.ToString();
        }
    }    
}